package com.hddznet.uniplatform.sm.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.hddznet.uniplatform.sm.config.cas.CasConfigData;
import com.hddznet.uniplatform.sm.dto.CasToken;
import com.hddznet.uniplatform.sm.service.IUserService;
import com.hddznet.uniplatform.sm.util.HdHttpUtils;
import com.hddznet.uniplatform.sm.util.HdStringUtils;
import com.hddznet.uniplatform.sm.vo.Result;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserServiceImpl implements IUserService{
	
	private final static String casUrl = "/hdl/oauth/v1.0/access.json";

	@Autowired
	private CasConfigData casConfigData;
	
	private Gson gson = new Gson();

	@Override
	public Result<CasToken> getUniwaterCasToken(String code) {
		log.info("casConfigData={}", casConfigData);
		if (StringUtils.isEmpty(code)) {
			return new Result<>("参数未获取");
		}
		if (casConfigData.getClientId() == null) {
			return  new Result<>("配置参数clientId缺失!");
		}
		if (casConfigData.getPrefixUrl() == null) {
			return  new Result<>("配置参数prefixUrl缺失!");
		}
		String prefixUrl = casConfigData.getPrefixUrl().trim().toLowerCase();
		if (!prefixUrl.startsWith("http")) {
			return  new Result<>("请检查配置参数prefixUrl");
		}
		if (prefixUrl.endsWith("/")) {
			prefixUrl = prefixUrl.substring(0, prefixUrl.length() - 1) + casUrl;
		} else {
			prefixUrl = prefixUrl + casUrl;
		}
		Map<String, String> params = new HashMap<>();
		params.put("grant_type", "authorization_code");
		params.put("client_id", casConfigData.getClientId());
		params.put("client_secret", HdStringUtils.getSHA256(casConfigData.getClientId() + "$" + casConfigData.getClientSecret()));
		params.put("redirect_uri", "http://127.0.0.1:8066/safetyManagement/cas/client/auth");
		params.put("code", code);
		Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
		String content = HdHttpUtils.doPost(prefixUrl, gson.toJson(params), header);
		CasToken casToken = gson.fromJson(content, CasToken.class);
		if (casToken.getAccessToken() == null) {
			return  new Result<>(content);
		}
		log.info("casToken={}", casToken);
		return  new Result<>(casToken);
	}
	
}
